package com.rj.bd.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rj.bd.entity.User;
import com.rj.bd.service.IUserService;

import cn.hutool.core.io.IoUtil; 
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

@Controller
@ResponseBody
@CrossOrigin
@RequestMapping("/excel")
public class ExcelConrtoller {
	
	@Autowired   //注入
	public IUserService userService;
	
	
	@RequestMapping("/upexcel")
	public Map<String, Object> Excel(HttpServletResponse response) throws UnsupportedEncodingException{
		
		
		Map<String, Object> json = new HashMap<String, Object>();
		
		List<User> list = userService.queryAll();
		System.out.println(list);
		//通过工具类创建write，默认创建xls格式
		ExcelWriter writer = ExcelUtil.getWriter();
		//自定义标题名
		writer.addHeaderAlias("uid", "学生id");
		writer.addHeaderAlias("unumber","学号");
		writer.addHeaderAlias("upassword", "密码");
		writer.addHeaderAlias("uname", "学生姓名");
		writer.addHeaderAlias("usex", "性别");
		
		//一次性写出内容，使用默认样式，强制输出标题
		writer.write(list,true);
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		
		String name = "学生信息";
		//name = URLEncoder(name,StandardCharsets.UTF_8);
		//name = URLEncoder(name,StandardCharsets.UTF_8);
		
		//response.setHeader("Content-Disposition","attachment;filename="+name+".xls");
		response.setContentType("application/x-download");//下面三行是关键代码，处理乱码问题  
		response.setCharacterEncoding("utf-8");  
		response.setHeader("Content-Disposition", "attachment;filename="+new String(name.getBytes("gbk"), "iso8859-1")+".xls");  
		
		ServletOutputStream out = null;
		
		try {
			out = response.getOutputStream();
			writer.flush(out,true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			//关闭write
			writer.close();
		}
		//关闭输出Servlet流
		IoUtil.close(out);
		
		json.put("code", "200");
		json.put("msg", "请求成功");
		json.put("data", list);
		
		return json;
	}

}

